package zzh.com.myapplication.apk;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * UpdateAppUtils 更新版本
 * 注意需要存储读写权限与联网权限
 *
 * @author zzh
 * @date
 */
public class UpdateAppUtils {
    private Context ct;//上下文
    private ProgressDialog progressDialog_update;//升级进度框

    private static UpdateAppUtils utils;

    /**
     * 单利模式
     *
     * @param ct
     * @return
     */
    public static UpdateAppUtils getUtlis(Context ct) {
        if (utils == null) {
            utils = new UpdateAppUtils(ct);
        }
        return utils;
    }

    /**
     * 下载线程
     */

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: // 下载完成，点击安装
                    if (progressDialog_update.getProgress() == 100) {
                        dismissUpdateDialog();
                        installAPK((File) msg.obj);
                    }
                    break;
                case 1://下载失败
                    dismissUpdateDialog();
                    showToast("下载失败，请稍后重试");
                    break;
                case 2://正在下载
                    showToast("正在下载中");
                    break;
                case 3://开始下载,下载中进度
                    float p = (float) msg.obj;
                    setDialogProgress((int) p);
                    break;

            }
        }
    };

    /**
     * 实例化更新工具类
     *
     * @param context 该页面的上下文
     */
    public UpdateAppUtils(Context context) {
        this.ct = context;
    }

    /**
     * 设置进度
     *
     * @param progress 进度值
     */
    private void setDialogProgress(int progress) {
        progressDialog_update.setProgress(progress);
    }

    /**
     * 显示吐司提示
     */
    private void showToast(String msg) {
        Toast.makeText(ct, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 取消进度框
     */
    private void dismissUpdateDialog() {
        if (progressDialog_update != null && (progressDialog_update.isShowing())) {
            progressDialog_update.dismiss();
        }
    }

    public void downloadApp() {
        updateDialog();
        startDownloadApp();
    }

    /**
     * 开始下载
     */
    private void startDownloadApp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    long totalSize;// 文件总大小
                    long downloadCount = 0;// 已经下载好的大小
                    String path;
                    // 下载apk，并且安装
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        path = ct.getExternalFilesDir(null) + "/apk";
                    } else {
                        path = ct.getFilesDir() + "/apk";
                    }

                    File filePath = new File(path);
                    if (!filePath.exists() || !filePath.isDirectory()) {
                        filePath.mkdirs();
                    }

                    File apkPath = new File(filePath, "cnkx.apk");
                    if (!apkPath.exists()) {
                        apkPath.createNewFile();
                    }
                    URL url = new URL("http://www.cnkx365.com/mobile/customhtml/cnkx.apk");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(10 * 1000);
                    httpURLConnection.setReadTimeout(10 * 1000);
                    httpURLConnection.setDoInput(true);
                    totalSize = httpURLConnection.getContentLength(); // 获取下载文件的size
                    int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
                    if (response == HttpURLConnection.HTTP_OK) {//200 是成功了
                        InputStream inputStream = httpURLConnection.getInputStream();
                        FileOutputStream outputStream = new FileOutputStream(apkPath, false);// 文件存在则覆盖掉
                        byte buffer[] = new byte[1024];
                        int readsize = 0;
                        while ((readsize = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, readsize);
                            downloadCount += readsize;// 时时获取下载到的大小
                            float progress = downloadCount * 1.0f / totalSize;
                            Message msg = handler.obtainMessage();
                            msg.what = 3;
                            msg.obj = progress * 100;
                            handler.sendMessage(msg);
                        }
                        httpURLConnection.disconnect();
                        outputStream.flush();
                        inputStream.close();
                        outputStream.close();
                        Message msg = handler.obtainMessage();
                        msg.what = 0;
                        msg.obj = apkPath;
                        handler.sendMessage(msg);
                    } else {
                        handler.sendEmptyMessage(1);
                    }
                } catch (Exception e) {
                    handler.sendEmptyMessage(1);
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 显示下载升级进度的对话框 updateDialog
     */
    private void updateDialog() {
        progressDialog_update = new ProgressDialog(ct);
        progressDialog_update.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog_update.setMessage("正在升级，请稍后");
        progressDialog_update.setMax(100);
        progressDialog_update.setCancelable(false);
        progressDialog_update.setCanceledOnTouchOutside(false);
        progressDialog_update.setProgress(0);
        progressDialog_update.show();
    }

    /**
     * 安装APP
     *
     * @param t File
     */
    private void installAPK(File t) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive");
        ct.startActivity(intent);
    }
}
